/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.uber.h3core.H3Core;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springblade.common.utils.PoiExcelUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.BuildingUserContractDTO;
import org.springblade.modules.admin.dto.BuildingUserDTO;
import org.springblade.modules.admin.dto.ProjectDTO;
import org.springblade.modules.admin.dto.building.BuildingUserElevatorDTO;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.mapper.es.ProjectDocumentMapper;
import org.springblade.modules.admin.service.BuildingService;
import org.springblade.modules.admin.service.ElevatorService;
import org.springblade.modules.admin.service.H3IndexService;
import org.springblade.modules.admin.vo.*;
import org.springblade.modules.admin.vo.brand.BrandVersionUploadResultVo;
import org.springblade.modules.admin.vo.brand.BuildingUserUploadVo;
import org.springblade.modules.admin.vo.building.BuildingUserElevatorDetailVo;
import org.springblade.modules.admin.vo.building.BuildingUserElevatorVo;
import org.springblade.modules.admin.vo.building.BuildingUserPageVo;
import org.springblade.modules.admin.vo.building.BuildingUserStatusVo;
import org.springblade.modules.system.entity.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 楼盘信息 控制器
 *
 * @author BladeX
 * @since 2021-05-11
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/building")
@Api(value = "楼盘信息", tags = "楼盘信息接口")
public class BuildingController extends BladeController {

	@Autowired
	private final BuildingService buildingService;
	@Autowired
	private final ElevatorService elevatorService;

	@Autowired
	private final ProjectDocumentMapper projectDocumentMapper;

	@Autowired
	private H3IndexService h3IndexService;

	/**
	 * 新增 小区
	 */
	@PostMapping()
	public R<Boolean> save(@RequestBody Building building) {
		if (StrUtil.isEmpty(building.getName())) {
			throw new ServiceException("项目名称不能为空!");
		}
		final String substring = building.getName().substring(0, 1);
		final String firstLetter = PinyinUtil.getFirstLetter(substring, "");
		building.setZhCode(firstLetter);

		//添加h3index
		try {
			buildingLocationToH3Index(building, null);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return R.status(buildingService.save(building));
	}

	/**
	 * 详情
	 */
	@GetMapping("/{id}")
	public R<BuildingVO> detail(@PathVariable Long id) {
		BuildingVO buildingVO = buildingService.selectBuilding(id);
		return R.data(buildingVO);
	}

	/**
	 * 分页
	 */
	@GetMapping("")
	public R<IPage<BuildingVO>> list(Building building, Query query) {
		IPage<BuildingVO> pages = buildingService.selectBuildingPage(Condition.getPage(query), building);
		return R.data(pages);
	}


	/**
	 * 修改
	 */
	@PutMapping("/{id}")
	public R<Boolean> update(@PathVariable Long id, @Valid @RequestBody Building building) {
		building.setId(id);
		elevatorService.update(Wrappers.<Elevator>lambdaUpdate()
			.set(Elevator::getBlockName, building.getBlockName()).set(Elevator::getUnitName, building.getUnitName()).eq(Elevator::getBuildingId, id));

		//修改h3index
		try {
			H3Index h3Index = h3IndexService.getOne(Wrappers.<H3Index>lambdaQuery().eq(H3Index::getBuildingId, id));
			if (ObjectUtil.isNull(h3Index)) {
				throw new ServiceException("h3index不存在");
			}
			buildingLocationToH3Index(building, h3Index.getId());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return R.status(buildingService.updateById(building));
	}

	/**
	 * 删除
	 */
	@DeleteMapping()
	public R<Boolean> remove(@RequestParam String ids) {

		final List<Elevator> list = elevatorService.list(new LambdaUpdateWrapper<Elevator>().eq(Elevator::getBuildingId, ids));
		if (list.size() > 0) {
			throw new ServiceException("该项目下存在关联的电梯,请删除电梯再删除项目");
		}

		// 新增 删除后缓存更新
		boolean b = buildingService.deleteLogic(Func.toLongList(ids));
		// 执行缓存更新
		buildingService.addRedisBuilding();

		// 2023-10-25 新增删除项目后，ES 删除对应 document
		projectDocumentMapper.deleteById(Long.valueOf(ids));

		//删除h3index
		h3IndexService.remove(Wrappers.<H3Index>lambdaQuery().eq(H3Index::getBuildingId, ids));

		return R.status(b);
	}

	@GetMapping("/listParentBuilding")
	public R<List<BuildingParentVo>> listParentBuilding(Long parentId) {
		if (parentId == null) {
			parentId = 0L;
		}
		List<Building> buildings = buildingService.list(Wrappers.<Building>lambdaQuery().eq(Building::getParentId, parentId).eq(Building::getIsDeleted, 0));
		List<BuildingParentVo> buildingParentVos = buildings.stream().map(e -> {
			BuildingParentVo buildingParentVo = new BuildingParentVo();
			buildingParentVo.setId(e.getId());
			buildingParentVo.setName(e.getName());
			return buildingParentVo;
		}).collect(Collectors.toList());
		return R.data(buildingParentVos);
	}


//	/**
//	 * 小区所有电梯列表
//	 */
//	@GetMapping("/list")
//	public R<List<BuildingVO>> list() {
//		List<BuildingVO> buildingVOList = buildingService.buildingVOList();
//		return R.data(buildingVOList);
//	}


	/**
	 * 更新adName
	 */
	@PostMapping("/batchUpdateAdname")
	public R<Boolean> batchUpdate(@RequestBody Building building) {
		return R.status(buildingService.updateById(building));
	}


	@GetMapping("/tree/list")
	public R<List<BuildingTreeVo>> treeList() {
		return R.data(buildingService.treeList());
	}

	@TenantIgnore
	@GetMapping("/select/list")
	@ApiOperation(value = "获取项目下拉列表（忽略租户）")
	public R<BuildingSelectListStatisticsVO> buildingSelectList() {
		return R.data(buildingService.buildingSelectList());
	}

	@TenantIgnore
	@GetMapping("/tlw/select/list")
	@ApiOperation(value = "梯联网-获取项目下拉列表（忽略租户）")
	public R<List<BuildingSelectListVO>> buildingTlwSelectList(PlanConfigSearchVO search) {
		return R.data(buildingService.buildingTlwSelectList(search));
	}

	@GetMapping("/init")
	public R<String> init() {
		List<Building> list = buildingService.list();
		for (Building building : list) {
			final String firstLetter = PinyinUtil.getFirstLetter(building.getName(), "");
			building.setZhCode(firstLetter);
		}

		final List<List<Building>> saveList = Lists.partition(list, 20);
		for (List<Building> list1 : saveList) {
			buildingService.updateBatchById(list1);
		}
		return R.data("初始化数据成功");
	}

	@GetMapping("/select/search/list")
	@ApiOperation(value = "获取项目下拉列表")
	public R<List<BuildingVO>> selectSearchList(BuildingVO search) {
		return R.data(buildingService.selectSearchList(search));
	}

	@GetMapping("/stagnation/init")
	@ApiOperation(value = "驻点启用初始值")
	public R<Boolean> stagnationInit() {
		boolean isSuccess = buildingService.stagnationInit();
		return R.data(isSuccess);
	}

	private void buildingLocationToH3Index(Building building, Long id) throws IOException {
		H3Index h3Index = new H3Index();
		if (ObjectUtil.isNotNull(id)) {
			h3Index.setId(id);
		}
		h3Index.setBuildingId(building.getId());

		for (int res = 5; res <= 10; res++) {
			H3Core h3Core = H3Core.newInstance();
			String index = h3Core.latLngToCellAddress(building.getLatitude().doubleValue(), building.getLongitude().doubleValue(), res);
			switch (res) {
				case 5:
					h3Index.setRes5Index(index);
					break;
				case 6:
					h3Index.setRes6Index(index);
					break;
				case 7:
					h3Index.setRes7Index(index);
					break;
				case 8:
					h3Index.setRes8Index(index);
					break;
				case 9:
					h3Index.setRes9Index(index);
					break;
				case 10:
					h3Index.setRes10Index(index);
					break;
				default:
					break;
			}
		}

		h3IndexService.saveOrUpdate(h3Index);
	}


	/**
	 * 获取项目客户单位的
	 *
	 * @return
	 */
	@GetMapping("getBuildingUserStatus")
	@ApiOperation("项目统计信息")
	public R<BuildingUserStatusVo> getBuildingUserStatus(Long id) {
		return R.data(buildingService.getBuildingStatus(id));
	}


	@PostMapping("buildDingList/v2")
	@ApiOperation(value = "项目列表分页-v2")
	public R<IPage<BuildingUserContract>> buildDingListV2(@RequestBody BuildingUserContractDTO buildingUserContractDTO) {
		return R.data(buildingService.buildDingListV2(buildingUserContractDTO));
	}

	@PostMapping("buildDingList/v2/down")
	@ApiOperation(value = "项目列表-v2")
	public void buildDingListDown(HttpServletResponse response, @RequestBody BuildingUserContractDTO buildingUserContractDTO) throws IOException {
		buildingUserContractDTO.setSize(0);
		List<BuildingUserContract> records = buildingService.buildDingListV2(buildingUserContractDTO).getRecords();
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title = CollUtil.newArrayList("合作状态", "项目类型", "项目名称", "项目别名", "楼栋信息", "电梯结构信息", "服务梯数", "脱保梯数", "问题梯数", "丢保梯数", "负责商务", "楼数", "梯数");
			rows.add(title);
			for (int i = 0; i < records.size(); i++) {
				List<String> row = new ArrayList<>();
				BuildingUserContract buildingUserContract = records.get(i);
				Integer joinHandsType = Convert.toInt(buildingUserContract.getJoinHandsType(), -1);
				if (joinHandsType == 1) {
					row.add("合作中");
				} else if (joinHandsType == 2) {
					row.add("丢保项目");
				} else if (joinHandsType == 3) {
					row.add("潜在项目");
				} else {
					row.add("--");
				}
				row.add(buildingUserContract.getBuildingTypeName());
				row.add(buildingUserContract.getBuildingName());
				row.add(buildingUserContract.getBuildingAliaName());
				row.add(Convert.toInt(buildingUserContract.getFloorType(), 0) == 0 ? "缺失" : "不缺失");
				row.add(Convert.toInt(buildingUserContract.getTemplatesCounts(), 0) == 0 ? "缺失" : "不缺失");
				row.add(Convert.toStr(buildingUserContract.getInTimeEleCounts()));
				row.add(Convert.toStr(buildingUserContract.getOutTimeEleCounts()));
				row.add(Convert.toStr(buildingUserContract.getQuestionEleCounts()));
				row.add(Convert.toStr(buildingUserContract.getDbEleCounts()));
				row.add(buildingUserContract.getUserName());
				row.add(Convert.toStr(buildingUserContract.getFloorCounts()));
				row.add(Convert.toStr(buildingUserContract.getElevatorCounts()));
				rows.add(row);
			}
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}
	}


	@GetMapping("elevator/status")
	@ApiOperation("电梯合同统计")
	public R<BuildingUserElevatorVo> elevatorStatus(Long id, @RequestParam(defaultValue = "0") Integer timeType) {
		return R.data(buildingService.elevatorStatus(id, timeType));
	}


	@PostMapping("elevatorList/v2")
	@ApiOperation("项目-电梯列表")
	public R<IPage<BuildingUserElevatorDetailVo>> elevatorListV2(@RequestBody BuildingUserElevatorDTO buildingUserElevatorDTO) {
		return R.data(buildingService.elevatorListV2(buildingUserElevatorDTO));
	}

	@PostMapping("elevatorList/down")
	@ApiOperation("客户单位-电梯列表")
	public void elevatordown(HttpServletResponse response, @RequestBody BuildingUserElevatorDTO buildingUserElevatorDTO) throws IOException {
		buildingUserElevatorDTO.setSize(0);
		List<BuildingUserElevatorDetailVo> records = buildingService.elevatorListV2(buildingUserElevatorDTO).getRecords();
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title;
			Integer type = Convert.toInt(buildingUserElevatorDTO.getType());
			if (type == 1) {
				title = CollUtil.newArrayList("项目名称", "电梯位置", "电梯别名", "使用单位", "品牌", "电梯来源", "重夺状态", "电梯维保状态", "合同业务状态", "维保状态细分", "电梯生命周期", "脱保问题", "断档问题", "待处理问题");
			} else if (type == 2) {
				title = CollUtil.newArrayList("项目名称", "电梯位置", "电梯别名", "使用单位", "品牌", "电梯来源", "重夺状态", "电梯维保状态", "合同业务状态", "维保状态细分", "电梯生命周期", "合同编号", "合同开始时间", "合同结束时间", "合同终止时间", "脱保时长");
			} else if (type == 3) {
				title = CollUtil.newArrayList("项目名称", "电梯位置", "电梯别名", "使用单位", "品牌", "电梯来源", "重夺状态", "电梯维保状态", "合同业务状态", "维保状态细分", "电梯生命周期", "合同编号", "合同开始时间", "合同结束时间", "合同终止时间");
			} else if (type == 4) {
				title = CollUtil.newArrayList("项目名称", "电梯位置", "电梯别名", "使用单位", "品牌", "电梯来源", "重夺状态", "电梯维保状态", "合同业务状态", "维保状态细分", "电梯生命周期", "合同编号", "合同创建时间", "合同开始时间", "合同结束时间", "合同附件");
			} else if (type == 5) {
				title = CollUtil.newArrayList("项目名称", "电梯位置", "电梯别名", "使用单位", "品牌", "电梯来源", "重夺状态", "电梯维保状态", "合同业务状态", "维保状态细分", "电梯生命周期", "合同编号", "合同开始时间", "合同结束时间", "合同终止时间", "距离脱保", "脱保时长");
			} else if (type == 6) {
				title = CollUtil.newArrayList("项目名称", "电梯位置", "电梯别名", "使用单位", "品牌", "电梯来源", "重夺状态", "电梯维保状态", "合同业务状态", "维保状态细分", "电梯生命周期", "确认丢保时间", "丢保原因", "丢保描述", "合同开始时间", "合同结束时间", "合同终止时间");
			} else {
				title = CollUtil.newArrayList("项目名称", "电梯位置", "电梯别名", "使用单位", "品牌", "电梯来源", "重夺状态", "电梯维保状态", "合同业务状态", "维保状态细分", "电梯生命周期", "合同编号", "合同开始时间", "合同结束时间", "合同终止时间", "确认丢保时间");
			}
			rows.add(title);
			for (int i = 0; i < records.size(); i++) {
				List<String> row = new ArrayList<>();
				BuildingUserElevatorDetailVo buildingUserElevatorDetailVo = records.get(i);
				row.add(Convert.toStr(buildingUserElevatorDetailVo.getBuildingName()));
				row.add(Convert.toStr(buildingUserElevatorDetailVo.getElevatorAddress()));
				row.add(Convert.toStr(buildingUserElevatorDetailVo.getElevatorAlias(),"--"));
				row.add(Convert.toStr(buildingUserElevatorDetailVo.getBuildingUserName(),"--"));
				row.add(Convert.toStr(buildingUserElevatorDetailVo.getBrandName()));
				Integer sourceStatus = Convert.toInt(buildingUserElevatorDetailVo.getSourceStatus(), -1);
				if (sourceStatus == 1) {
					row.add("安装");
				} else if (sourceStatus == 2) {
					row.add("新接");
				} else {
					row.add("--");
				}
				Integer regainStatus = Convert.toInt(buildingUserElevatorDetailVo.getRegainStatus(), -1);
				if (regainStatus == 1) {
					row.add("未重夺");
				} else if (regainStatus == 2) {
					row.add("重夺");
				} else if (regainStatus == 3) {
					row.add("--");
				} else {
					row.add("--");
				}
				Integer maintainStatus = Convert.toInt(buildingUserElevatorDetailVo.getMaintainStatus(), -1);
				if (maintainStatus == -1 || maintainStatus == 1) {
					row.add("脱保");
				} else {
					row.add("在保");
				}

				if (maintainStatus == 1) {
					row.add("丢保");
				} else if (maintainStatus == 2) {
					row.add("在保（合同范围内）");
				} else if (maintainStatus == 3) {
					row.add("在保（合同范围外）");
				} else if (maintainStatus == 4) {
					row.add("在保（拟定在保）");
				} else if (maintainStatus == 5) {
					row.add("脱保(合同终止)");
				} else if (maintainStatus == 6) {
					row.add("脱保(合同到期)");
				} else if (maintainStatus == 7) {
					row.add("脱保(下份合同待生效)");
				} else if (maintainStatus == 8) {
					row.add("-");
				}
				Integer contractStatus = Convert.toInt(buildingUserElevatorDetailVo.getContractStatus(), -1);
				if (contractStatus == 1) {
					row.add("未生效");
				} else if (contractStatus == 2) {
					row.add("已生效");
				} else if (contractStatus == 3) {
					row.add("已到期");
				} else if (contractStatus == 3) {
					row.add("已终止");
				} else {
					row.add("--");
				}
				Integer lifeStatus = Convert.toInt(buildingUserElevatorDetailVo.getLifeStatus(), -1);
				if (lifeStatus == 1) {
					row.add("未注册");
				} else if (lifeStatus == 2) {
					row.add("在用");
				} else if (lifeStatus == 3) {
					row.add("停用");
				} else if (lifeStatus == 4) {
					row.add("安装改造维修中");
				} else if (lifeStatus == 5) {
					row.add("注销");
				} else if (lifeStatus == 6) {
					row.add("报废");
				} else {
					row.add("--");
				}
				if (type == 1) {
					row.add(maintainStatus == 1 ? "1" : "0");
					row.add(buildingUserElevatorDetailVo.getIsGap().toString());
					Integer quSize = (maintainStatus == 1 ? 1 : 0) + buildingUserElevatorDetailVo.getIsGap();
					row.add(quSize.toString());
				}
				if (type == 2) {
					row.add(Convert.toStr(buildingUserElevatorDetailVo.getContractNo()));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getBeginTime(), "yyyy-MM-dd"));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getEndTime(), "yyyy-MM-dd"));
					if (buildingUserElevatorDetailVo.getStopTime() != null) {
						row.add(DateUtil.format(buildingUserElevatorDetailVo.getStopTime(), "yyyy-MM-dd"));
					} else {
						row.add("-");
					}
					Date date = Convert.toDate(buildingUserElevatorDetailVo.getStopTime(), buildingUserElevatorDetailVo.getEndTime());
					long day = DateUtil.betweenDay(new Date(), date, true);
					if (day >= 3 && day < 7) {
						row.add("已脱保3天");
					} else if (day >= 7 && day < 15) {
						row.add("已脱保7天");
					} else if (day >= 15 && day < 30) {
						row.add("已脱保15天");
					} else if (day >= 30 && day < 60) {
						row.add("已脱保30天");
					} else if (day >= 30) {
						row.add("已脱保60天以上");
					} else {
						row.add("已脱保" + day + "天以上");
					}
				}
				if (type == 3) {
					row.add(Convert.toStr(buildingUserElevatorDetailVo.getContractNo()));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getBeginTime(), "yyyy-MM-dd"));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getEndTime(), "yyyy-MM-dd"));
					if (buildingUserElevatorDetailVo.getStopTime() != null) {
						row.add(DateUtil.format(buildingUserElevatorDetailVo.getStopTime(), "yyyy-MM-dd"));
					} else {
						row.add("-");
					}
				}

				if (type == 4) {
					row.add(Convert.toStr(buildingUserElevatorDetailVo.getContractNo()));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getBeginTime(), "yyyy-MM-dd"));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getEndTime(), "yyyy-MM-dd"));
					if (buildingUserElevatorDetailVo.getContractExt() == null) {
						row.add("0");
					} else {
						row.add(Convert.toStr(buildingUserElevatorDetailVo.getContractExt().size(), "0"));
					}
				}


				if (type == 5) {
					row.add(Convert.toStr(buildingUserElevatorDetailVo.getContractNo()));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getBeginTime(), "yyyy-MM-dd"));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getEndTime(), "yyyy-MM-dd"));
					if (buildingUserElevatorDetailVo.getStopTime() != null) {
						row.add(DateUtil.format(buildingUserElevatorDetailVo.getStopTime(), "yyyy-MM-dd"));
					} else {
						row.add("-");
					}
					Date date = Convert.toDate(buildingUserElevatorDetailVo.getStopTime(), buildingUserElevatorDetailVo.getEndTime());

					if (System.currentTimeMillis() < date.getTime()) {
						long day = DateUtil.betweenDay(new Date(), date, true);
						if (day <= 7) {
							row.add("已不足7天");
						} else if (day <= 30) {
							row.add("不足30天");
						} else if (day <= 60) {
							row.add("不足60天");
						} else if (day <= 90) {
							row.add("不足90天");
						} else {
							row.add("--");
						}
					} else {
						row.add("-");
					}
					if (System.currentTimeMillis() > date.getTime()) {
						long day = DateUtil.betweenDay(new Date(), date, true);
						if (day >= 3 && day < 7) {
							row.add("已脱保3天");
						} else if (day >= 7 && day < 15) {
							row.add("已脱保7天");
						} else if (day >= 15 && day < 30) {
							row.add("已脱保15天");
						} else if (day >= 30 && day < 60) {
							row.add("已脱保30天");
						} else if (day >= 30) {
							row.add("已脱保60天以上");
						} else {
							row.add("已脱保" + day + "天以上");
						}
					} else {
						row.add("-");
					}
				}

				if (type == 6) {
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getTuoDate(), "yyyy-MM-dd"));
					Integer tuoType = Convert.toInt(buildingUserElevatorDetailVo.getTuoType(), -1);
					if (tuoType == 1) {
						row.add("服务不达标");
					} else if (tuoType == 2) {
						row.add("竞对签约");
					} else if (tuoType == 3) {
						row.add("客户暂停使用电梯");
					} else if (tuoType == 4) {
						row.add("其他");
					}
					row.add(Convert.toStr(buildingUserElevatorDetailVo.getTuoTypeDesc(), "--"));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getBeginTime(), "yyyy-MM-dd"));
					row.add(DateUtil.format(buildingUserElevatorDetailVo.getEndTime(), "yyyy-MM-dd"));
					if (buildingUserElevatorDetailVo.getStopTime() != null) {
						row.add(DateUtil.format(buildingUserElevatorDetailVo.getStopTime(), "yyyy-MM-dd"));
					} else {
						row.add("-");
					}
				}

				if (type == 0) {
					row.add(Convert.toStr(buildingUserElevatorDetailVo.getContractNo()));

					if (buildingUserElevatorDetailVo.getBeginTime() == null) {
						row.add("--");
					} else {
						row.add(DateUtil.format(buildingUserElevatorDetailVo.getBeginTime(), "yyyy-MM-dd"));
					}
					if (buildingUserElevatorDetailVo.getEndTime() == null) {
						row.add("--");
					} else {
						row.add(DateUtil.format(buildingUserElevatorDetailVo.getEndTime(), "yyyy-MM-dd"));
					}
					if (buildingUserElevatorDetailVo.getStopTime() != null) {
						row.add(DateUtil.format(buildingUserElevatorDetailVo.getStopTime(), "yyyy-MM-dd"));
					} else {
						row.add("-");
					}
					if (buildingUserElevatorDetailVo.getTuoDate() != null) {
						row.add(DateUtil.format(buildingUserElevatorDetailVo.getTuoDate(), "yyyy-MM-dd"));
					} else {
						row.add("-");
					}
				}
				rows.add(row);
			}
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}
	}

	/**
	 * 功能描述: 发送响应流方法
	 */
	private void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
